package com.app.reportproblem;

import java.io.IOException;

import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.PlusClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;


public class LoginWithGoogleActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener, com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks{

	private static final int REQUEST_CODE_RESOLVE_ERR = 9000;

    private ProgressDialog mConnectionProgressDialog;
    private PlusClient mPlusClient;
    private ConnectionResult mConnectionResult;

    private static final String TAG = "Google Plus Demo";
    //private static final String CLIENT_ID = "942245617448-vk98bjj7ru3n3b9k62th4mvt3f9refeo.apps.googleusercontent.com";
    //private static final String SCOPE = "audience:server:client_id:" + CLIENT_ID;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login_with_google);
		
		mPlusClient = new PlusClient.Builder(this, this, this)
					.setActions("http://schemas.google.com/LoginWithGoogleActivity")
					.setScopes("PLUS_LOGIN")
					.build();
		
		 mConnectionProgressDialog = new ProgressDialog(this);
	     mConnectionProgressDialog.setMessage("Signing in...");
		
	     loginG();
	}
	
	
	

	@Override
	protected void onStart() {
		super.onStart();
		mPlusClient.connect();
	}


	@Override
	protected void onStop() {
		super.onStop();
		mPlusClient.disconnect();
	}

	


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == REQUEST_CODE_RESOLVE_ERR && resultCode == RESULT_OK) {
            mConnectionResult = null;
            mPlusClient.connect();
        }
		
	}




	@Override
	public void onConnectionFailed(ConnectionResult result) {
		 if(mConnectionProgressDialog.isShowing()) {
	            // The user clicked on the sign-in button already. Start to resolve
	            // connection errors. Wait until onConnected() to dismiss the 
	            // connection dialog.

	            if(result.hasResolution()) {
	                try {
	                    result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
	                } catch(SendIntentException e) {
	                    mPlusClient.connect();
	                }
	            }
	        }

	        // Save the result
	        mConnectionResult = result;
	}

	@Override
	public void onConnected(Bundle connectionHint) {
		/*String accountName = mPlusClient.getAccountName();
        Toast.makeText(this, accountName, Toast.LENGTH_LONG).show();
        mConnectionProgressDialog.dismiss();
        
        Thread th = new Thread(new Runnable() {
			
			@Override
			public void run() {
//				  getAccessToken();
			      Log.i("DATA", "ACCESS: "+getAccessToken());
			}
		});
        th.start();*/
		
		// Retrieve the oAuth 2.0 access token.
		final Context context = this.getApplicationContext();
		AsyncTask task = new AsyncTask() {
			@Override
			protected Object doInBackground(Object... params) {
				String scope = "oauth2:" + Scopes.PLUS_LOGIN;
				try {
					// We can retrieve the token to check via
					// tokeninfo or to pass to a service-side
					// application.
					String token = GoogleAuthUtil.getToken(context,
						mPlusClient.getAccountName(), scope);
				} catch (UserRecoverableAuthException e) {
					// This error is recoverable, so we could fix this
					// by displaying the intent to the user.
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (GoogleAuthException e) {
					e.printStackTrace();
				}
		    return null;
			}
		};
		task.execute((Void) null);
		
	}

	@Override
	public void onConnectionSuspended(int cause) {
		
	}

	@Override
	public void onDisconnected() {
		
	}
	
	void loginG() {
		 if(mConnectionResult == null) {
             mConnectionProgressDialog.show();
         } else {
             try {
                 mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
             } catch(SendIntentException e) {
                 // Try connecting again
                 mConnectionResult = null;
                 mPlusClient.connect();
             }
         }
	}
	
	private String getAccessToken() {
		String WEB_APPLICATION_CLIENT_ID = "942245617448-vk98bjj7ru3n3b9k62th4mvt3f9refeo.apps.googleusercontent.com";
	    String scopes = String.format("audience:server:client_id:" + WEB_APPLICATION_CLIENT_ID );

	    String code = null;
	    try {
	         code = GoogleAuthUtil.getToken(
	                 LoginWithGoogleActivity.this,                             // Context context
	                 mPlusClient.getAccountName(),     // String accountName
	                    scopes
	                );
	    } catch (IOException transientEx) {
	      // network or server error, the call is expected to succeed if you try again later.
	      // Don't attempt to call again immediately - the request is likely to
	      // fail, you'll hit quotas or back-off.
	        Log.e("getAccessToken()", "[ERROR] IOException: " + transientEx);
	    } catch (UserRecoverableAuthException e) {
	           // Recover
	        Log.e("getAccessToken()", "[ERROR] UserRecoverableAuthException: " + e);
	        code = null;
	    } catch (GoogleAuthException authEx) {
	      // Failure. The call is not expected to ever succeed so it should not be
	      // retried.
	        Log.e("getAccessToken()", "[ERROR] GoogleAuthException: " + authEx);
	    } catch (Exception e) {
	        Log.e("getAccessToken()", "[ERROR] Exception: " + e);
	      throw new RuntimeException(e);
	    }
	    return code;
	}
}
